<?php

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Gregwar\Captcha\CaptchaBuilder;

class CommonApi extends Controller
{   
    /**
    * 上传到图片到七牛云
    * @param  Request $request  [description]
    * @param  string  $fileName [description]
    * @return [type]            [description]
    */
    public static function uploadToQiNiu(Request $request, $fileName = 'pic')
    {

        $file = $request->file($fileName);
        
        if(!$file){
            return [
            'status' => 4403,
            'msg'    => '没有上传文件',
            ];
        }
        if(!$file->isValid()){
            return [
            'status' => 4401,
            'msg'    => '上传文件不合法',
            ];
        }

        // 需要填写你的 Access Key 和 Secret Key,具体查看七牛后台
        $accessKey = env('QINIU_ACCESSKEY');
        $secretKey = env('QINIU_SECRETKEY');

        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);


        // 要上传的空间,这是在你七牛后台设置的
        $bucket = env('QINIU_BUCKET');

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $filePath = $file->getRealPath();

        // 上传到七牛后保存的文件名
        $date = time().uniqid();
        $key = $date.'.'.$file->getClientOriginalExtension();

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();

        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($res, $err) = $uploadMgr->putFile($token, $key, $filePath);

        if ($err !== null) {

            return [
                'code' => 400,
                'msg' => '失败',
                'data' => $err
            ];

        } else {
            $info = [
            'code' => 200,
            'msg'    => '上传成功',
            'data'   => $res
            ];

            return $info;
        }

    }

    /**
    * @CustomPagination 手动创建分页器
    * @param  object $request  请求实例
    * @param  array $data      要分页的数据
    * @param  int   $perPage   每页显示条数
    * @return object 对数据分页后的分页对象
    */
    public static function CustomPagination(Request $request, $data, $perPage = 5)
    {

        $current_page = $request->input('page');
        $current_page = $current_page <= 0 ? 1 :$current_page;

        $item = array_slice($data, ($current_page-1)*$perPage, $perPage);
        $total = count($data);

        $paginator =new LengthAwarePaginator($item, $total, $perPage, $current_page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

        return $paginator;
    }

    /**
     * 生成验证码
     * @param  Request $request 
     * @return 图片
     */
    public function buildCode(Request $request)
    {
        $builder = new CaptchaBuilder;
        $builder->build();

        //获取验证码内容
        $phrase = $builder->getPhrase();

        //将验证码存到session
        $request->session()->put('code', $phrase);
        \Session::save();

        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
        exit;
    }

    /**
     * 验证验证码是否正确
     * @param Request $request      
     * @param string  $formCodeName 输入验证码的input标签的name属性值
     */
    public static function CheckCode(Request $request, $formCodeName = 'code')
    {
        $userCode = $request->input($formCodeName);

        if ( session('code') == $userCode ) {
            return  true;
        }

        return false;
    }



}
